package org.itboys.mobile.controller.weixin;

import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;
import org.itboys.commons.CommonConstants;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.dto.SundayMemberSessionDto;
import org.itboys.mobile.service.mongo.front.SundayFrontCollectionService;
import org.itboys.mobile.service.mongo.front.SundayFrontMemberService;
import org.itboys.mobile.service.mysql.front.SundayFrontProductService;
import org.itboys.mobile.util.AccountIdHoldUtils;
import org.itboys.mobile.util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhangyang on 2017/12/20.
 * 圣代_收藏_controller_weixin
 */
@Controller
@RequestMapping("/sunday/weixin/collection")
public class SundayWeiXinCollectionController extends BaseController{

    @Autowired
    private SundayFrontCollectionService collectionService;
    @Autowired
    private SundayFrontProductService productService;
    @Autowired
    private SundayFrontMemberService memberService ;

    /**
     * 收藏主页
     * @param request
     * @return
     */
    @RequestMapping(value="/index", method= RequestMethod.GET)
    public String index(HttpServletRequest request,
                        HttpServletResponse response,
                        Model model,
                        @ApiParam(required=true, name="type", value="收藏的类型 1-商品,2-用户,3-我的店铺（就是产品）")@RequestParam(value = "type", required = true)Integer type
                        ){
        try{
            AccountIdHoldUtils.getSessionMember(request);
            model.addAttribute("type",type);
            return "/aigou/weixin/collection/index";
        }catch (Exception e){
            logger.error("/sunday/weixin/collection/index----e="+e.getMessage());
            e.printStackTrace();
            return "/aigou/weixin/error";
        }
    }

    /**
     * 获取数据
     * @param request
     * @param type  收藏的类型 1商品
     * @param pageSize
     * @param pageNumber
     * @param sort
     * @param order
     */
    @RequestMapping(value="/select", method= RequestMethod.POST)
    @ApiOperation(value="【微信端】获取收藏数据")
    public String select(
            HttpServletRequest request,Model model,
            @ApiParam(required=true, name="type", value="收藏的类型 1-商品,2-用户,3-我的店铺（就是产品）")@RequestParam(value = "type", required = true)Integer type,
            @ApiParam(required = true, name = "pageSize", value = "分页参数。每页数量。默认20") @RequestParam(value = "pageSize", required = true) String pageSize,
            @ApiParam(required = true, name = "pageNumber", value = "分页参数。第几页。默认1") @RequestParam(value = "pageNumber", required = true) String pageNumber,
            @ApiParam(required = false, name = "sort", value = "排序参数。字段名称。默认为空") @RequestParam(value = "sort", required = false) String sort,
            @ApiParam(required = false, name = "order", value = "排序参数。。默认为空。ASC正序/DESC倒序") @RequestParam(value = "order", required = false) String order){
        try{
            SundayMemberSessionDto memberSessionDto = AccountIdHoldUtils.getSessionMember(request);
            List list = new ArrayList();
            //查询收藏的商品、店铺的产品
            if(type== SundayCommonConstants.collection_type_product||type== SundayCommonConstants.collection_type_fenxiao){
                 list = productService.getCollection(request,memberSessionDto.getId(),type);
            }else if(type== SundayCommonConstants.collection_type_member){
                list = memberService.getCollection(request,memberSessionDto.getId());
            }

            model.addAttribute("list",list);
            return "/aigou/weixin/collection/data";
        }catch (Exception e){
            logger.error("/sunday/weixin/collection/select----e="+e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 新增收藏
     * @param request
     * @param type  收藏类型 1商品
     * @param otherId   被收藏（商品）的id
     */
    @RequestMapping(value="/save", method= RequestMethod.POST)
    @ApiOperation(value="【微信端】增加收藏或取消")
    public void save(HttpServletRequest request,
                     HttpServletResponse response,
                     @ApiParam(required=true, name="type", value="收藏类型 1-商品,2-用户,3-我的店铺（就是产品）")@RequestParam(value = "type", required = true)Integer type,
                     @ApiParam(required=true, name="otherId", value="被收藏（商品）的id")@RequestParam(value = "otherId", required = true)Long otherId){
                    // @ApiParam(required=true, name="memberId", value="登录用户id")@RequestParam(value = "memberId", required = true)Long memberId
        try{
            SundayMemberSessionDto member = AccountIdHoldUtils.getSessionMember(request);
            collectionService.saveCollection(member.getId(),type,otherId);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/weixin/collection/save----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }

    /**
     * 取消收藏
     * @param request
     * @param type  收藏类型 1商品
     * @param otherIds   被收藏（商品）的ids
     */
    @RequestMapping(value="/delete", method= RequestMethod.POST)
    @ApiOperation(value="【微信端】删除收藏")
    public void delete(HttpServletRequest request,
                       HttpServletResponse response,
                       @ApiParam(required=true, name="type", value="收藏类型 1商品,2用户，3-我的店铺（就是产品）")@RequestParam(value = "type", required = true)Integer type,
                       @ApiParam(required=true, name="otherIds", value="被收藏（商品，用户）ID的集合，例如：otherIds=1,2,3,4")@RequestParam(value = "otherIds", required = true)List<Long> otherIds){
        try{
            Long memberId = AccountIdHoldUtils.getSessionMember(request).getId();
            collectionService.deleteCollection(memberId,type,otherIds);
            ResponseMessage.success();
        }catch (Exception e){
            String msg = CommonConstants.ERROMSG;
            Integer code=CommonConstants.FAIL_CODE;
            //自定义异常（签名错误）
            if(e.getClass().getSimpleName().equalsIgnoreCase("ErrorException")){
                msg=e.getMessage();
                //token已过期
            }else  if(e.getClass().getSimpleName().equalsIgnoreCase("TokenException")){
                code=CommonConstants.TOKEN_CODE;
                msg=CommonConstants.TOKENMSG;
            }else{
                logger.error("/sunday/weixin/collection/delete----e="+e.getMessage());
            }
            e.printStackTrace();
            ResponseMessage.error(code,msg);
        }
    }
}
